package com.loan.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.loan.common.excel.ExcelListener;
import com.loan.common.excel.ExcelResult;
import com.loan.common.exception.ServiceException;
import com.loan.common.helper.LoginHelper;
import com.loan.common.utils.spring.SpringUtils;
import com.loan.system.domain.AddressEntity;
import com.loan.system.domain.vo.AddressImportVo;
import com.loan.system.service.AddressService;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author shiguang on 2022/9/8 9:57
 */
@Slf4j
public class AddressImportListener extends AnalysisEventListener<AddressImportVo> implements ExcelListener<AddressImportVo> {

    private final AddressService addressService;

    private final String operName;

    private final Boolean isUpdateSupport;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public AddressImportListener(Boolean isUpdateSupport) {
        this.addressService = SpringUtils.getBean(AddressService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.operName = LoginHelper.getUsername();
    }

    @Override
    public ExcelResult<AddressImportVo> getExcelResult() {
        return new ExcelResult<AddressImportVo>() {
            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<AddressImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }

    @Override
    public void invoke(AddressImportVo addressImportVo, AnalysisContext analysisContext) {
        //根据code查询地址是否存在
        AddressEntity address = this.addressService.selectByCode(addressImportVo.getCode());
        try {
            if (ObjectUtil.isNull(address)) {
                address = BeanUtil.toBean(addressImportVo, AddressEntity.class);
                String code = address.getCode();
                String str = code.substring(code.length() - 2, code.length());
                if (str.equals("00")){
                    address.setParentId(0L);
                }else{
                    code = code.substring(0,code.length()-2) + "00";
                    AddressEntity addressEntity = this.addressService.selectByCode(code);
                    if (ObjectUtil.isNull(address)){
                        failureNum++;
                        failureMsg.append("<br/>").append(failureNum).append("、地址 ").append(address.getName()).append(" 的父类不存在");
                        return;
                    }else{
                        address.setParentId(addressEntity.getId());
                    }
                }
                address.setCreateBy(operName);
                addressService.insertAddress(address);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、地址 ").append(address.getName()).append(" 导入成功");
            } else if (isUpdateSupport) {
                address.setUpdateBy(operName);
                //根据code修改
                address.setName(addressImportVo.getName());
                addressService.updateAddress(address);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、地址 ").append(address.getName()).append(" 更新成功");
            }else{
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、地址 ").append(address.getName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、地址 " + address.getName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
